<template>
  <div class="schools-container">
    <div class="banner">
      <div class="banner-content">
        <h1>京剧流派</h1>
        <p>百年传承，艺术精华</p>
      </div>
    </div>
    
    <div class="introduction-section">
      <div class="intro-content">
        <h2>什么是京剧流派</h2>
        <p>京剧流派是指在京剧艺术发展过程中，由杰出艺术家创立的具有独特艺术风格、表演特点和审美标准的艺术体系。流派的形成是京剧艺术成熟与繁荣的重要标志，也是传统艺术传承与创新的重要途径。</p>
        <p>京剧流派通常以创始人的姓氏命名，如"梅派"、"程派"、"谭派"等。每个流派在唱腔、做工、念白等方面都有其独特的风格特点，形成了京剧艺术的丰富多彩的表现形式。</p>
      </div>
    </div>
    
    <!-- <div class="schools-relation-section">
      <h2>行当与流派关系图</h2>
      <div v-loading="loading" class="chart-container">
        <div class="chart-controls">
          <el-radio-group v-model="chartType" size="medium" @change="updateChartView">
            <el-radio-button label="relation">关系图</el-radio-button>
            <el-radio-button label="category">行当分类</el-radio-button>
          </el-radio-group>
        </div>
        <div id="relationChart" class="echarts-container"></div>
      </div>
    </div> -->
    
    <div class="featured-schools-section">
      <h2>主要流派介绍</h2>
      <div class="school-cards">
        <el-card v-for="school in displayedSchools" :key="school.id" class="school-card" shadow="hover">
          <div class="school-header">
            <h3>{{ school.name }}</h3>
            <div class="school-tags">
              <el-tag size="small" type="danger">{{ school.category }}</el-tag>
              <el-tag size="small" type="info">创始于{{ school.foundedTime }}</el-tag>
            </div>
          </div>
          
          <div class="school-content">
            <div class="school-image">
              <img :src="school.image" :alt="school.name">
            </div>
            <div class="school-info">
              <div class="school-founder">
                <span class="label">创始人:</span>
                <span class="value">{{ school.founder }}</span>
              </div>
              <div class="school-desc">{{ school.description }}</div>
              <div class="school-features">
                <div class="feature-item">
                  <span class="feature-label">唱腔特点:</span>
                  <span class="feature-value">{{ school.singingFeature }}</span>
                </div>
                <div class="feature-item">
                  <span class="feature-label">表演风格:</span>
                  <span class="feature-value">{{ school.performanceStyle }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="school-footer">
            <el-button type="text" @click="showSchoolDetail(school.id)">查看详情</el-button>
          </div>
        </el-card>
      </div>
      
      <div class="view-more-container" v-if="featuredSchools.length > initialDisplayCount">
        <div 
          class="view-more-btn"
          @click="toggleShowMore">
          {{ showAllSchools ? '收起' : '查看更多' }}
        </div>
      </div>
    </div>
    
    <!-- 流派详情对话框 -->
    <el-dialog
      :title="currentSchool.name"
      :visible.sync="dialogVisible"
      width="70%"
      center>
      <div class="school-detail-content" v-if="currentSchool">
        <div class="detail-header">
          <div class="detail-image">
            <img :src="currentSchool.image" :alt="currentSchool.name">
          </div>
          <div class="detail-basic">
            <div class="detail-item">
              <span class="label">创始人:</span>
              <span class="value">{{ currentSchool.founder }}</span>
            </div>
            <div class="detail-item">
              <span class="label">形成时间:</span>
              <span class="value">{{ currentSchool.foundedTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">主要行当:</span>
              <span class="value">{{ currentSchool.category }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-description">
          <h4>流派简介</h4>
          <p>{{ currentSchool.description }}</p>
        </div>
        
        <div class="detail-features">
          <h4>流派特点</h4>
          <div class="feature-list">
            <div class="feature-item" v-for="(feature, index) in currentSchool.features" :key="index">
              <div class="feature-name">{{ feature.name }}</div>
              <div class="feature-desc">{{ feature.description }}</div>
            </div>
          </div>
        </div>
        
        <div class="detail-artists">
          <h4>代表艺术家</h4>
          <div class="artists-list">
            <div class="artist-item" v-for="artist in currentSchool.artists" :key="artist.id" @click="goToArtist(artist.id)">
              <div class="artist-avatar">
                <img :src="artist.avatar" :alt="artist.name">
              </div>
              <div class="artist-name">{{ artist.name }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'SchoolsVue',
  data() {
    return {
      // 主要流派数据
      featuredSchools: [],
      
      // 流派行当映射
      categoryIdToNameMap: {},
      
      // 对话框控制
      dialogVisible: false,
      currentSchool: {},
      loading: false,
      
      // 控制显示的流派数量
      initialDisplayCount: 9,
      showAllSchools: false,
      
      // 缓存行当名称
      categoryNameCache: {}
    }
  },
  computed: {
    // 根据显示状态返回要显示的流派
    displayedSchools() {
      if (this.showAllSchools) {
        return this.featuredSchools;
      } else {
        return this.featuredSchools.slice(0, this.initialDisplayCount);
      }
    }
  },
  mounted() {
    document.title = '京剧苑 - 京剧流派';
    window.scrollTo(0, 0);
    // 先初始化行当ID到名称的映射
    this.initCategoryIdToNameMap();
    this.loadFeaturedSchools();
  },
  methods: {
    // 初始化行当ID到名称的映射
    initCategoryIdToNameMap() {
      // 预先请求所有行当数据
      service.get('/api/content/category/getCategoryList', {
        params: {
          pageNum: 1,
          pageSize: 100
        }
      }).then(res => {
        if (res.code === 200 && res.data && res.data.list) {
          // 构建行当ID到名称的映射
          res.data.list.forEach(category => {
            this.categoryIdToNameMap[category.categoriesId] = category.categoriesName;
            this.categoryNameCache[category.categoriesId] = category.categoriesName;
          });
          
          // 更新现有数据中的行当名称
          this.updateExistingCategoryNames();
        }
      }).catch(error => {
        console.error('获取行当数据失败:', error);
      });
    },
    
    // 更新现有数据中的行当名称
    updateExistingCategoryNames() {
      // 更新featuredSchools中的行当名称
      this.featuredSchools.forEach((school, index) => {
        if (school.categoryIds) {
          const categoryIds = school.categoryIds.split(',');
          const categoryNames = categoryIds.map(id => this.categoryIdToNameMap[id] || id);
          
          const updatedSchool = { ...school };
          updatedSchool.category = categoryNames.join('/');
          this.featuredSchools.splice(index, 1, updatedSchool);
        }
      });
      
      // 更新currentSchool中的行当名称
      if (this.currentSchool && this.currentSchool.categoryIds) {
        const categoryIds = this.currentSchool.categoryIds.split(',');
        const categoryNames = categoryIds.map(id => this.categoryIdToNameMap[id] || id);
        this.currentSchool.category = categoryNames.join('/');
      }
    },
    
    // 加载主要流派介绍
    loadFeaturedSchools() {
      service.get('/api/content/school/getSchoolList', {
        params: {
          pageNum: 1,
          pageSize: 100 // 获取所有流派，然后在前端进行处理
        }
      }).then(res => {
        if (res.code === 200) {
          const schoolList = res.data.list;
          
          // 处理流派数据
          this.featuredSchools = schoolList.map(school => {
            let categoryName = '';
            
            // 处理行当名称
            if (school.category) {
              const categoryIds = school.category.split(',');
              
              // 使用已缓存的行当名称
              const categoryNames = categoryIds.map(id => this.categoryIdToNameMap[id] || id);
              categoryName = categoryNames.join('/');
              
              // 如果有未映射的ID，异步获取行当名称
              if (categoryNames.some(name => /^\d+$/.test(name))) {
                this.fetchCategoryNames(school.schoolId, categoryIds);
              }
            }
            
            // 构建流派特点
            const features = [];
            if (school.features && Array.isArray(school.features)) {
              school.features.forEach(feature => {
                features.push({
                  name: feature.title,
                  description: feature.description
                });
              });
            }
            
            // 加载流派特点
            this.loadSchoolFeatures(school.schoolId, features);
            
            // 加载艺术家数据
            this.loadSchoolArtists(school.schoolId, school);
            
            return {
              id: school.schoolId,
              name: school.schoolName,
              category: categoryName,
              categoryIds: school.category, // 保存原始ID以便后续更新
              founder: school.founder,
              foundedTime: school.foundedTime,
              image: school.image,
              description: school.description,
              singingFeature: school.features && school.features[0] ? school.features[0].description : '暂无数据',
              performanceStyle: school.features && school.features[1] ? school.features[1].description : '暂无数据',
              features: features,
              artists: [] // 将通过loadSchoolArtists异步加载
            };
          });
        } else {
          this.$message.error('获取流派数据失败');
        }
      }).catch(error => {
        console.error('获取流派数据失败:', error);
        this.$message.error('获取流派数据失败');
      });
    },
    
    // 获取行当名称并更新流派数据
    fetchCategoryNames(schoolId, categoryIds) {
      const categoryNamePromises = categoryIds.map(categoryId => {
        // 检查缓存中是否已有此行当名称
        if (this.categoryNameCache[categoryId]) {
          return Promise.resolve(this.categoryNameCache[categoryId]);
        }
        
        // 否则从API获取
        return service.get(`/api/content/category/getCategoryById/${categoryId}`)
          .then(res => {
            if (res.code === 200 && res.data) {
              // 缓存结果
              const categoryName = res.data.categoriesName;
              this.categoryNameCache[categoryId] = categoryName;
              this.categoryIdToNameMap[categoryId] = categoryName;
              return categoryName;
            }
            return categoryId; // 如果获取失败，返回原ID
          })
          .catch(() => categoryId); // 出错也返回原ID
      });
      
      // 等待所有行当名称获取完成
      Promise.all(categoryNamePromises).then(names => {
        // 更新流派的行当名称
        const schoolIndex = this.featuredSchools.findIndex(s => s.id === schoolId);
        if (schoolIndex !== -1) {
          const updatedSchool = { ...this.featuredSchools[schoolIndex] };
          updatedSchool.category = names.join('/');
          this.featuredSchools.splice(schoolIndex, 1, updatedSchool);
        }
        
        // 更新currentSchool中的行当名称
        if (this.currentSchool && this.currentSchool.id === schoolId) {
          this.currentSchool.category = names.join('/');
        }
      });
    },
    
    // 切换显示全部/部分流派
    toggleShowMore() {
      this.showAllSchools = !this.showAllSchools;
    },
    
    // 加载流派特点数据
    loadSchoolFeatures(schoolId, featuresArray) {
      service.get(`/api/content/school/getSchoolFeatures/${schoolId}`).then(res => {
        if (res.code === 200 && Array.isArray(res.data)) {
          // 清空原数组并添加新数据
          featuresArray.length = 0;
          
          res.data.forEach(feature => {
            featuresArray.push({
              name: feature.title,
              description: feature.description
            });
          });
          
          // 更新特定流派的唱腔特点和表演风格
          const schoolIndex = this.featuredSchools.findIndex(s => s.id === schoolId);
          if (schoolIndex !== -1) {
            const school = this.featuredSchools[schoolIndex];
            
            // 设置默认特点
            school.singingFeature = '暂无数据';
            school.performanceStyle = '暂无数据';
            
            // 查找唱腔特点和表演风格
            const singingFeature = res.data.find(f => f.title.includes('唱腔') || f.title.includes('声音') || f.title.includes('音色'));
            const performanceFeature = res.data.find(f => f.title.includes('表演') || f.title.includes('风格') || f.title.includes('动作'));
            
            if (singingFeature) {
              school.singingFeature = singingFeature.description;
            }
            
            if (performanceFeature) {
              school.performanceStyle = performanceFeature.description;
            }
            
            // 更新流派数据
            this.featuredSchools.splice(schoolIndex, 1, school);
          }
        }
      }).catch(error => {
        console.error('获取流派特点失败:', error);
      });
    },
    
    // 加载流派相关艺术家
    loadSchoolArtists(schoolId) {
      service.get('/api/content/artist/getArtistList', {
        params: {
          pageNum: 1,
          pageSize: 100,
          schoolId: schoolId
        }
      }).then(res => {
        if (res.code === 200) {
          const artists = res.data.list.map(artist => ({
            id: artist.artistId,
            name: artist.artistName,
            avatar: artist.image
          }));
          
          // 更新特定流派的艺术家数据
          const schoolIndex = this.featuredSchools.findIndex(s => s.id === schoolId);
          if (schoolIndex !== -1) {
            this.featuredSchools[schoolIndex].artists = artists;
          }
        }
      }).catch(error => {
        console.error('获取流派艺术家失败:', error);
      });
    },
    
    showSchoolDetail(schoolId) {
      // 从featuredSchools中查找流派
      let school = this.featuredSchools.find(s => s.id === schoolId);
      
      if (!school) {
        // 如果在featuredSchools中没有找到，则直接从API获取
        this.loadSchoolById(schoolId);
        return;
      }
      
      this.currentSchool = school;
      this.dialogVisible = true;
    },
    
    // 根据ID加载特定流派
    loadSchoolById(schoolId) {
      this.loading = true;
      
      service.get(`/api/content/school/getSchoolById/${schoolId}`).then(res => {
        if (res.code === 200 && res.data) {
          const school = res.data;
          let categoryName = '';
          
          // 获取行当名称
          if (school.category) {
            const categoryIds = school.category.split(',');
            
            // 使用缓存中的行当名称
            const categoryNames = categoryIds.map(id => this.categoryIdToNameMap[id] || id);
            categoryName = categoryNames.join('/');
            
            // 如果有未映射的ID，异步获取行当名称
            if (categoryNames.some(name => /^\d+$/.test(name))) {
              this.fetchCategoryNames(schoolId, categoryIds);
            }
          }
          
          // 构建当前流派对象
          this.currentSchool = {
            id: school.schoolId,
            name: school.schoolName,
            category: categoryName,
            categoryIds: school.category,
            founder: school.founder,
            foundedTime: school.foundedTime,
            image: school.image,
            description: school.description,
            features: [],
            artists: []
          };
          
          // 加载特点和艺术家
          this.loadSchoolFeatures(schoolId, this.currentSchool.features);
          this.loadSchoolArtists(schoolId, this.currentSchool);
          
          this.dialogVisible = true;
        } else {
          this.$message.error('获取流派详情失败');
        }
        
        this.loading = false;
      }).catch(error => {
        console.error('获取流派详情失败:', error);
        this.loading = false;
        this.$message.error('获取流派详情失败');
      });
    },
    
    goToArtist(artistId) {
      this.$router.push({ name: 'ArtistDetail', params: { id: artistId }});
    }
  }
}
</script>

<style scoped>
.schools-container {
  min-height: 100vh;
  padding-bottom: 50px;
  background-color: #f9f5f0;
}

.banner {
  height: 500px;
  background-image: url('../assets/opera_school.png');
  background-size: cover;
  background-position: center;
  position: relative;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(139, 0, 0, 0.7), rgba(0, 0, 0, 0.5));
}

.banner-content {
  position: relative;
  z-index: 1;
  text-align: center;
  color: #fff;
}

.banner-content h1 {
  font-size: 4rem;
  font-family: 'STXingkai', 'STZhongsong', serif;
  margin-bottom: 15px;
  color: #FFD700;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.6);
  letter-spacing: 10px;
}

.banner-content p {
  font-size: 1.4rem;
  max-width: 600px;
  margin: 0 auto;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.6);
  letter-spacing: 3px;
}

.introduction-section {
  padding: 60px 10%;
  background-color: #fff;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 40px;
}

.intro-content {
  max-width: 900px;
  margin: 0 auto;
}

.intro-content h2 {
  font-size: 2.4rem;
  color: #8B0000;
  margin-bottom: 30px;
  font-family: 'STZhongsong', serif;
  position: relative;
  display: inline-block;
}

.intro-content h2::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background-color: #8B0000;
}

.intro-content p {
  font-size: 1.2rem;
  line-height: 2;
  color: #333;
  margin-bottom: 20px;
  text-align: justify;
}

.featured-schools-section {
  padding: 60px 8%;
  background-color: transparent;
}

.featured-schools-section h2 {
  text-align: center;
  font-size: 2.4rem;
  color: #8B0000;
  margin-bottom: 50px;
  font-family: 'STZhongsong', serif;
  position: relative;
  display: inline-block;
  margin-left: 50%;
  transform: translateX(-50%);
}

.featured-schools-section h2::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background-color: #8B0000;
}

.school-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.school-card {
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
  border: none;
  background-color: rgba(255, 255, 255, 0.95);
}

.school-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 30px rgba(139, 0, 0, 0.15);
}

.school-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.school-header h3 {
  font-size: 1.8rem;
  color: #8B0000;
  margin: 0 0 12px;
  font-family: 'STZhongsong', serif;
}

.school-tags .el-tag {
  margin-right: 8px;
  border-radius: 4px;
}

.school-content {
  display: flex;
  margin-bottom: 20px;
}

.school-image {
  width: 80px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 15px;
  border: 1px solid #e0e0e0;
}

.school-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.school-image:hover img {
  transform: scale(1.05);
}

.school-info {
  flex: 1;
}

.school-founder {
  margin-bottom: 12px;
}

.label {
  font-weight: bold;
  color: #666;
  margin-right: 5px;
}

.value {
  color: #333;
}

.school-desc {
  font-size: 1rem;
  line-height: 1.7;
  color: #555;
  margin-bottom: 15px;
  height: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.school-features .feature-item {
  margin-bottom: 8px;
  background-color: #f9f5f0;
  padding: 8px 12px;
  border-radius: 4px;
}

.feature-label {
  font-weight: bold;
  color: #8B0000;
  margin-right: 5px;
}

.feature-value {
  color: #333;
  font-size: 0.95rem;
}

.school-footer {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.school-footer .el-button {
  color: #8B0000;
  font-weight: bold;
}

/* 流派详情对话框样式 */
.school-detail-content {
  padding: 30px;
}

.detail-header {
  display: flex;
  margin-bottom: 40px;
}

.detail-image {
  width: 180px;
  height: 230px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 40px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.detail-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.detail-basic {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.detail-item {
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.detail-description,
.detail-features,
.detail-artists {
  margin-bottom: 40px;
}

.detail-description h4,
.detail-features h4,
.detail-artists h4 {
  font-size: 1.6rem;
  color: #8B0000;
  margin-bottom: 20px;
  font-family: 'STZhongsong', serif;
  position: relative;
  display: inline-block;
}

.detail-description h4::after,
.detail-features h4::after,
.detail-artists h4::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 50px;
  height: 2px;
  background-color: #8B0000;
}

.detail-description p {
  font-size: 1.1rem;
  line-height: 1.9;
  color: #444;
}

.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.feature-item {
  background-color: #f9f5f0;
  padding: 18px;
  border-radius: 8px;
  border-left: 4px solid #8B0000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.feature-name {
  font-weight: bold;
  color: #8B0000;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.feature-desc {
  color: #555;
  line-height: 1.7;
}

.artists-list {
  display: flex;
  flex-wrap: wrap;
}

.artist-item {
  width: 120px;
  margin: 0 20px 30px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.artist-item:hover {
  transform: translateY(-5px);
}

.artist-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 auto 12px;
  border: 3px solid #8B0000;
  box-shadow: 0 5px 15px rgba(139, 0, 0, 0.2);
}

.artist-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.artist-item:hover .artist-avatar img {
  transform: scale(1.08);
}

.artist-name {
  text-align: center;
  font-size: 1rem;
  color: #333;
  font-weight: bold;
}

.view-more-container {
  text-align: center;
  margin-top: 50px;
}

.view-more-btn {
  display: inline-block;
  font-size: 1.1rem;
  padding: 12px 25px;
  color: #8B0000;
  font-weight: bold;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
}

.view-more-btn:hover {
  transform: translateY(-3px);
  color: #6a0000;
}

.view-more-btn i {
  margin-left: 8px;
  font-size: 14px;
  transition: transform 0.3s;
}

.view-more-btn:hover i {
  transform: translateY(3px);
}

.view-more-btn::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 50%;
  height: 2px;
  background-color: #8B0000;
  transition: width 0.3s;
}

.view-more-btn:hover::after {
  width: 70%;
}

@media (max-width: 1200px) {
  .school-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 992px) {
  .detail-header {
    flex-direction: column;
    align-items: center;
  }
  
  .detail-image {
    margin-right: 0;
    margin-bottom: 25px;
  }
  
  .detail-basic {
    text-align: center;
  }
  
  .feature-list {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .banner-content h1 {
    font-size: 3rem;
    letter-spacing: 5px;
  }
  
  .banner-content p {
    font-size: 1.2rem;
    letter-spacing: 2px;
  }
  
  .intro-content h2,
  .featured-schools-section h2 {
    font-size: 2rem;
  }
  
  .school-cards {
    grid-template-columns: 1fr;
  }
  
  .introduction-section,
  .featured-schools-section {
    padding: 40px 5%;
  }
}

@media (max-width: 576px) {
  .banner {
    height: 250px;
  }
  
  .banner-content h1 {
    font-size: 2.5rem;
    letter-spacing: 3px;
  }
  
  .banner-content p {
    font-size: 1rem;
  }
  
  .detail-image {
    width: 150px;
    height: 200px;
  }
  
  .artist-item {
    width: 100px;
  }
  
  .artist-avatar {
    width: 80px;
    height: 80px;
  }
}
</style> 